<?php

class GroupModel {
    
    /**
     * @var \PDO
     */
    private $db;
    
    function __construct($db) {
        $this->db = $db;
    }

    public function all($get){
        $order_by = $this->buildOrder($get);
        $where = $this->buildWhere($get);
        $prepare = $this->db->prepare("SELECT id, name FROM groups $where $order_by");
        $prepare->execute();
        return $prepare->fetchAll();
    }
    
    private function buildWhere($get){
        if ( array_key_exists('fc', $get) ){
            return " WHERE ({$get['fc']} LIKE '%{$get['fv']}%') ";
        }
        return '';
    }
    
    private function buildOrder($get){
        if (array_key_exists('sc', $get) ){
            $scol = $get['sc'];
            $sord = $get['so'];
            return " ORDER BY $scol $sord ";
        }
        return '';
    }
    
    public function add($name){
        $prepare = $this->db->prepare('INSERT INTO groups (id, name) VALUES(null, :name)');
        $prepare->bindParam('name', $name, PDO::PARAM_STR);
        $prepare->execute();
    }
    
    public function edit($id, $name){
        $prepare = $this->db->prepare('UPDATE groups SET name = :name WHERE id = :id');
        $prepare->bindParam('name', $name, PDO::PARAM_STR);
        $prepare->bindParam('id', $id, PDO::PARAM_INT);
        $prepare->execute();
    }
    
    public function del($id){
        $prepare = $this->db->prepare('DELETE FROM groups WHERE id = :id');
        $prepare->bindParam('id', $id, PDO::PARAM_INT);
        $prepare->execute();
    }
    
    public function findById($id){
        $prepare = $this->db->prepare('SELECT id, name FROM groups WHERE id = :id');
        $prepare->bindParam('id', $id);
        $prepare->execute();
        $result = $prepare->fetchAll();
        if ( count($result) === 0 ){
            return null;
        }
        return $result[0];
    }
    
}
